<template>
  <el-form ref="queryForm" :inline="true" :model="params" :label-width="serachConfig.labelWidth || '90px'">
    <el-form-item 
      v-for="(item,index) of column" 
      :key="index" 
      :label="item.searchLabel || item.label"
      :prop="item.prop"
      :label-width="item.labelWidth || ''"
    >
      <slot v-if="slot[item.prop]" :params="params" :name="item.prop"></slot>
      <template v-else>
        <el-select v-if="item.type=='select'" v-model="params[item.searchKey || item.prop]" :placeholder="item.placeholder" :disabled="item.disabled" :style="{width:(item.valWidth || 200) +'px'}">
          <el-option label="全部" value=""></el-option>
          <el-option 
            v-for="(v,index) of item.selectArr"
            :key="index"  
            :disabled="v.disabled" 
            :label="item.selectProp ? v[item.selectProp.label] : v['label']" :value="item.selectProp ? v[item.selectProp.value] : v['value']"></el-option>
        </el-select>
        <el-select v-if="item.type=='selectCheck'" v-model="params[item.searchKey || item.prop]" :placeholder="item.placeholder" :disabled="item.disabled" multiple :style="{width:(item.valWidth || 200) +'px'}">
          <el-option 
            v-for="(v,index) of item.selectArr"
            :key="index"  
            :disabled="v.disabled" 
            :label="item.selectProp ? v[item.selectProp.label] : v['label']" :value="item.selectProp ? v[item.selectProp.value] : v['value']"></el-option>
        </el-select>
        <el-date-picker
          v-if="item.type =='date'"
          v-model="params[item.searchKey || item.prop]"
          :format="item.format || 'YYYY-MM-DD'"
          type="date"
          placeholder="选择日期"
        />
        <el-date-picker
          v-if="item.type =='daterange'"
          v-model="params[item.searchKey || item.prop]"
          :format="item.format || 'YYYY-MM-DD'"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
        <el-date-picker
          v-if="item.type =='datetimerange'"
          v-model="params[item.searchKey || item.prop]"
          :default-time="item.defaultTime || [new Date(2024,12,12,0,0,0), new Date(2024,12,12,23,59,59)]"
          :format="item.format || 'YYYY-MM-DD'"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
        <el-form-item v-if="item.type=='model'">
          <el-input v-model="params[item.searchKey || item.prop]" clearable :placeholder="item.placeholder" :disabled="item.disabled"  :style="{width:(item.valWidth || 200) +'px'}" @clear="clensParams(item,params)" @click="modelClick(item)">
            <!-- <template #append>
              <el-icon><DeleteFilled /></el-icon>
            </template> -->
          </el-input>
        </el-form-item>
        <el-input v-if="!item.type || item.type=='input'" v-model="params[item.searchKey || item.prop]" clearable :placeholder="item.placeholder || '请输入'+item.label" :disabled="item.disabled" :style="{width:(item.valWidth || 200) +'px'}" @keyup.enter="query"></el-input>
      </template>
    </el-form-item>
    <el-form-item v-if="isOption">
      <el-button :loading="loading" @click="reset"> 重置</el-button>
      <el-button v-if="serachConfig.isQuery" :loading="loading" type="primary" @click="query"> 查询</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>

  import moment from 'moment'
  import {getObjType as judgeType} from '../utils';
  const props = defineProps({
    column: {
      type: Array,
      default: () => []
    },
    serachConfig:{
      type:Object,
      default:()=>({
        isDefault:true
      })
    },
    isOption:{
      type:Boolean,
      default:true
    }
  })
  props.column.forEach(item=>{
    if(item.getSelectData){
      const p = new Promise((resolve,reject)=>{
        item.getSelectData(item,resolve,reject)
      })
      p.then(res=>{
        item.selectArr = res
      })
    }
  })
  const serachConfig = computed(()=>{
    const config = props.serachConfig
    if(config.isQuery===undefined)config.isQuery = true
    return config
  })
  const slot = useSlots()
  const emit = defineEmits(['query','reset','model','modeEmpty'])
  const params = reactive({})
  const loading = ref(false)
  // 当前配置对象变化时重置配置
  watch(()=> props.column,()=>{
    rsetParams()
  },{deep:true,immediate:true})
  // 删除弹窗选择参数
  function clensParams(item,params){
    params[item.prop] = ''
    // 需要遵循规则 比如供应商展示名称名称为：supplierName  ,那么对应的key就是 supplierId 这样才能在删除名称的同时删除对应的id
    let key = item.prop
    key = key.substr(0,key.length-4)
    let keyId = key+'Id'
    let code = key+'Code'
    params[keyId] && (params[keyId] = '')
    params[code] && (params[code] = '')
    emit('modeEmpty',item,params)
  }
  function modelClick(item){
    console.log('触发model');
    emit('model',item,params)
  }
  // 创建初始字段和默认参数
  function handelProp(item,isDefault = true){
    if(item.type == 'daterange' || item.type == 'datetimerange' || item.type == 'selectCheck'){
      return isDefault ? item.default || [] : [] 
    }
    return isDefault ? item.default || '' : ''
  }
  /**
  * isDefault 是否读取默认值
  */
  function rsetParams(isDefault){
    props.column.forEach(item=>{
      clensParams(item,params)
      params[item.searchKey?item.searchKey:item.prop] = handelProp(item,isDefault)
    })
  }
  /**
   * 获取表单数据
   */
  function getFormData(){
    const queryParam = { ...params }
        // 将时间对象转为本地字符串时间
    for (const key in queryParam) {
      if (typeof queryParam[key] != 'object') continue
      // 单个时间
      if (judgeType(queryParam[key]) == 'date') {
        const data = props.column.find((item) => item.prop == key)
        queryParam[key] = moment(queryParam[key]).format(data?.format || 'YYYY-MM-DD')
      }
      // 时间段
      if (judgeType(queryParam[key]) == 'array' && judgeType(queryParam[key][0])=='date' && judgeType(queryParam[key][1])=='date') {
        if(!queryParam[key].length){
          delete queryParam[key]
          continue
        }
        const data = props.column.find((item) => item.prop == key)
        const timeArrKey = data?.daterange || []
        const timeArr = queryParam[key]
        let isdel
        timeArrKey.forEach((k, index) => {
          if(k==key)isdel=true
          queryParam[k] = moment(timeArr[index]).format(data?.format || 'YYYY-MM-DD')
        })
        // if (timeArrKey.length && !isdel) delete queryParam[key]
        delete queryParam[key]
      }
    }
    Object.keys(queryParam).forEach(key=> {
      queryParam[key]==='' && delete queryParam[key]
      if(Array.isArray(queryParam[key]) && !queryParam[key].length)  delete queryParam[key]
    })
    return queryParam
  }
  const query = ()=>{
    loading.value = true
    setTimeout(() => loading.value = false, 500);
    emit('query',getFormData())
  }
  const reset = ()=>{
  // Object.keys(params).forEach(key=> params[key]='')
    loading.value = true
    setTimeout(() => loading.value = false, 500);
    rsetParams(props.serachConfig.isDefault)
    emit('reset',getFormData())
  }
  defineExpose({
    getFormData,
    reset,
    query
  })
</script>

<style lang="scss" scoped>

</style>